<?php
namespace app\admin\controller;

use app\common\model\ArticleCateModel;
use app\common\model\ArticleModel;
use app\common\model\PlatformGiftModel;
use app\common\model\WebFileHistoryModel;
use app\common\model\WebMenuModel;
use think\File;
use think\Filesystem;

class Web extends Common
{

    const TEMP_VAR = "_temp";

    public function menu()
    {
        $input_data = input();
        $list =[];


        WebMenuModel::getAllData($input_data)->each(function($item,$index)use(&$list){
            $linkChild = $item->getRelation('linkChild');
            $info = $item->apiFullInfo();
            $info['child_list'] = [];
            foreach ($linkChild as $vo){
                $childInfo = $vo->apiFullInfo();
                $childInfo['child_list'] = [];
                $linkChild2 = $vo->getRelation('linkChild');
                foreach ($linkChild2 as $child2){
                    $childInfo['child_list'][] =  $child2->apiFullInfo();
                }
                $info['child_list'][]  = $childInfo;
            }
            array_push($list,$info);
        });

        return $this->_resData(1,'获取成功',['list'=>$list ]);
    }
    //删除数据
    public function menuDel()
    {
        $id = $this->request->param('id',0,'int');
        try{
            WebMenuModel::actionDel(['id'=>$id]);
        }catch (\Exception $e){
            return $this->_resData(0,$e->getMessage());
        }
        return $this->_resData(1,'操作成功');
    }

    public function handleSaveData()
    {
        $php_input = input();
        try{
            WebMenuModel::handleSaveData($php_input);
        }catch (\Exception $e){
            return $this->_resData(0,$e->getMessage());
        }
        return $this->_resData(1,'操作成功');
    }

    //修改信息
    public function menuModInfo()
    {
        $php_input = input();
        try{
            WebMenuModel::modInfo($php_input);
        }catch (\Exception $e){
            return $this->_resData(0,$e->getMessage());
        }
        return $this->_resData(1,'操作成功');
    }


    public function template()
    {
        $root_path = root_path(WebMenuModel::VIEW_ROOT);
        return $this->_resData(1,'获取成功',[
            'list' => $this->_getFiles($root_path,WebMenuModel::VIEW_ROOT),
        ]);
    }
    public function templateFile()
    {
        $path = input('path');
        $mode = input('mode','create','trim');
        try{
            if(empty($path) || !is_string($path)) throw new \Exception('请输入路径');
            if(!preg_match('/^[0-9a-zA-Z-_]+$/', $path)) throw new \Exception('路径只能为【英文字母、数字】组成');
            if(empty($mode) || !is_string($path)) throw new \Exception('请选择模式');

            //路径处理
            if($path[0]!='/'){
                $path = '/'.$path;
            }
            $temp_path = $path.self::TEMP_VAR;
            if(stripos('.',$path)===false){
                $path .='.html';
                $temp_path .='.html';
            }


            $full_path = root_path(WebMenuModel::VIEW_ROOT).$path;
            $full_temp_path = root_path(WebMenuModel::VIEW_ROOT).$temp_path;
            if($mode=='del'){
                if(!file_exists($full_path)) throw new \Exception('文件不存在,无法删除');
                $state = unlink($full_path);
                if(!$state) throw new \Exception('文件删除失败');
            }else{
                if(file_exists($full_path)) throw new \Exception('文件已存在,无法继续创建');
                //  创建文件

                file_put_contents($full_temp_path, $temp_path);
                $state = file_put_contents($full_path, $path);
                if(!$state) throw new \Exception('文件创建失败');
            }




        }catch (\Exception $e){
            return $this->_resData(0,$e->getMessage());
        }
        return $this->_resData(1,'操作成功');
    }

    public function templateFileContent()
    {
        $path = input('path');
        $full_path = root_path(WebMenuModel::VIEW_ROOT).$path;
        if(!file_exists($full_path)){
            file_put_contents($full_path,$path);
        }


        return $this->_resData(1,'获取成功',[
            'content' => file_get_contents($full_path),
        ]);
    }

    public function templateRelease()
    {
        $path = input('path');
        $tempPath = input('tempPath');
        $full_path = root_path(WebMenuModel::VIEW_ROOT).$path;
        $full_temp_path = root_path(WebMenuModel::VIEW_ROOT).$tempPath;
        if(!file_exists($full_path) || !file_exists($full_temp_path)) throw new \Exception('文件不存在,请刷新页面重新尝试');
        $temp_content = file_get_contents($full_temp_path);
        $state=file_put_contents($full_path,$temp_content);
        if(!$state) throw new \Exception('保存异常');
        return $this->_resData(1,'保存成功');
    }

    public function templateFileContentSave()
    {
        $path = input('path');
        $content = input('content','', 'trim');
        $full_path = root_path(WebMenuModel::VIEW_ROOT).$path;
        if(!file_exists($full_path)) throw new \Exception('文件不存在,请重新选择');
        //保存数据到数据库
        WebFileHistoryModel::record($path,$content); //保存历代版本

        file_put_contents($full_path,$content);



        return $this->_resData(1,'保存成功',[
        ]);
    }

    public function fileContent()
    {
        $path = root_path().input('path');
        if(!file_exists($path)) throw new \Exception('文件不存在,请重新选择');
        return $this->_resData(1,'获取成功',[
            'content'=> file_get_contents($path),
        ]);
    }
    public function fileContentSave()
    {
        $path = input('path');
        $content = input('content','', 'trim');
        if(!file_exists($path)) throw new \Exception('文件不存在,请重新选择');
        file_put_contents($path,$content);



        return $this->_resData(1,'保存成功',[
        ]);
    }


    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
     */
    private function _getFiles($path, $default_path ='', &$files = array())
    {
        if (!is_dir($path)) return null;
        if(substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);

        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    $this->_getFiles($path2, $default_path, $files);
                } else {
                    $path_route = str_replace('\\','',substr($path2, strlen(root_path($default_path))));
                    if($path_route[0]!='/'){
                        $path_route = '/'.$path_route;
                    }
                    if(stripos($path_route,self::TEMP_VAR.'.html')) continue;

                    $temp_route = str_replace('.html',self::TEMP_VAR.'.html',$path_route);
                    $last_mod_time = filemtime($path2);
                    $files[] = array(
                        'url'=> request()->domain().WebMenuModel::VIEW_ROOT_DIR.$path_route,
                        'temp_url'=> request()->domain().WebMenuModel::VIEW_ROOT_DIR.$temp_route,
                        'path'=> $path_route,
                        'tempPath'=> $temp_route,
                        'filesize' => round((filesize($path2) / 1024 / 1024),2),
                        'name'=> $file,
                        'update_time'=> empty($last_mod_time)?'--':date('Y-m-d H:i:s',$last_mod_time)
                    );
                }
            }
        }
        return $files;
    }

}
